package maitreEsclavexN;
import java.net.InetAddress;
import java.rmi.*;
import java.rmi.server.*;

import solveurSolo.Solveur;

import jeu.*;

public class Calcule extends UnicastRemoteObject implements CalculeInterface,Runnable{
    
	private static final long serialVersionUID = 42L;
	
    //private Listener listener;
    private Game game;
    private String maitre;
    private String port;
    private boolean a_calculer = false;
    private Object drapeau = new Object();
    
    public Calcule(String nomMaitre, String numeroPort) throws RemoteException {
    	this.maitre = nomMaitre;
    	this.port = numeroPort;
    	System.out.print("jesxiste, je vis");
	}

   
    
   public void run(){
	   System.out.println("je me lance");
	   for(;;){
		   synchronized(drapeau){
			   if(a_calculer){
				   System.out.println("je calcule");
				   Solveur.solve(game,0);
				 
				   
				   try{
				   AgregationInterface somme = 
						(AgregationInterface) Naming.lookup("rmi://"+maitre+":"+port+"/Service");
					    somme.agrege(game,InetAddress.getLocalHost().getHostName());
				   }
				   catch(Exception e){
					   e.printStackTrace();
				   }
				   a_calculer= false;
				   
				   
			   }
			   
		   }
		   try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	   }
   }


    
    public void calcule(Game g) throws RemoteException {
    	System.out.print("jai recu quelque chose");
    	synchronized (drapeau) {
    		System.out.println(" et je le traite.");
        	this.game =g;
        	this.a_calculer = true;	
		}
    	
    	
    }
}
